const fs = require('fs');
const multer = require('multer')
const uploadModel = require('../../models/resources/index');
const intformat = require('biguint-format')
  , FlakeId = require('flake-idgen')
function createId() {
  var flakeIdGen = new FlakeId();
  return intformat(flakeIdGen.next(), 'dec')
}
//判断路径是否存在，不存在则创建
var createFolder = function (folder) {
  try {
    fs.accessSync(folder);
  } catch (e) {
    fs.mkdirSync(folder);
  }
};

var uploadFolder = 'D://upload/'; //设置文件存储路径
createFolder(uploadFolder);
// 通过 filename 属性定制
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadFolder);    // 保存的路径
  },
  filename: function (req, file, cb) {
    var singfileArray = file.originalname.split('.');
    var fileExtension = singfileArray[singfileArray.length - 1];
    var fileNmae = createId()
    cb(null, fileNmae + '.' + fileExtension);
  }
});
function fileFilter(req, file, cb) {
  let originalname = file.originalname
  var reg = /\.(png|jpg|gif|jpeg|webp)$/;
  if (reg.test(originalname)) {
    cb(null, true)
  } else {
    cb(new Error('文件类型错误'))
  }
  // 这个函数应该调用 `cb` 用boolean值来
  // 指示是否应接受该文件

  // 拒绝这个文件，使用`false`，像这样:
  // cb(null, false)

  // 接受这个文件，使用`true`，像这样:

  // 如果有问题，你可以总是这样发送一个错误:
  // cb(new Error('I don\'t have a clue!'))
}
var upload = multer({ storage: storage, fileFilter: fileFilter })
const singleMidle = upload.single("singleFile");//一次处理一张
const multipleMidle = upload.array("multipleFile", 9);//一次最多处理5张
const fieldsMidle = upload.fields([
  { name: "fieldSingleFile", maxCount: 1 },
  { name: "fieldArrayFile", maxCount: 4 }
]);
// 读取失败默认图
function getImgErr(req, res) {
  let path = 'D:/upload/1.png'
  fs.readFile(path, (err, data) => {
    res.end(Buffer.from(data, 'binary'));
  })
}
class Upload {
  constructor() {
  }
  //单图片上传
  uploadImg = async (req, res, next) => {
    singleMidle(req, res, async function (err) {
      try {
        if (err) {
          throw new Error(err.message || '上传文件失败')
        }
        if (!req.file) {
          throw new Error('请选择文件')
        }
        const newUpLoad = {
          res_id: req.file.filename.split('.')[0],
          path: req.file.path,
          date: Date.now().toString(),
          category_info: '6794922327323705344'
        }
        let rbody = {
          code: 0,
          data: newUpLoad.res_id,
          message: '上传成功'
        }
        console.log(newUpLoad);
        await uploadModel.create(newUpLoad)
        res.send(rbody)
      } catch (err) {
        let error = {
          code: -1,
          message: '上传失败'
        }
        res.send(error)
      }
    })
  }
  multipleUp = async (req, res, next) => {
    return new Promise((resolve, reject) => {
      multipleMidle(req, res, async function (er56r) {
        try {
          if (err) {
            throw new Error(err.message || '上传文件失败')
          }
          let body = {
            code: 0,
            data: req.files,
            message: "上传成功"
          }
          res.send(body);
        } catch (err) {
          reject(err)
        }
      })
    })
  }
  fieldUp = async (req, res, next) => {
    fieldsMidle(req, res, async function (err) {
      try {
        if (err) {
          throw new Error(err.message || '上传文件失败')
        }
        let body = {
          code: 0,
          message: "上传成功"
        }
        res.send(body);
      } catch (err) {
        this.error(`上传文件失败${err}`)
        let error = {
          code: -1,
          message: err.message || '操作失败'
        }
        res.send(error)
      }
    })
  }
  // 根据id获取图片信息
  getImgById = async (req, res, next) => {
    let id = req.params.id
    try {
      let { path } = await uploadModel.findOne({ res_id: id })
      console.log(path);
      fs.readFile(path, (err, data) => {
        if (err) {
          return getImgErr(req, res)
        }
        res.end(Buffer.from(data, 'binary'));
      })
    } catch (error) {
      console.log(error.message);
      getImgErr(req, res)
      // res.sendStatus(404)
    }
  }
}
module.exports = new Upload()